package com.hoshiicloud.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.GoodsProperties;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.goods.GoodsPropertiesMapper;
import com.hoshiicloud.goods.service.GoodsCategoryPropertiesService;
import com.hoshiicloud.goods.service.GoodsPropertiesService;
import com.hoshiicloud.goods.service.GoodsPropertiesValuesService;
import com.hoshiicloud.goods.vo.GoodsPropertiesPageVo;
import com.hoshiicloud.goods.vo.GoodsPropertiesVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品属性 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class GoodsPropertiesServiceImpl extends ServiceImpl<GoodsPropertiesMapper, GoodsProperties> implements GoodsPropertiesService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private GoodsCategoryPropertiesService goodsCategoryPropertiesService;

    @Autowired
    private GoodsPropertiesValuesService goodsPropertiesValuesService;


    @Override
    @Logable(authName = "商品管理-商品属性管理-分页查询商品属性")
    @Cacheable(cacheNames = "GoodsProperties", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<GoodsPropertiesPageVo> getPage(Page<GoodsPropertiesPageVo> page, Wrapper<GoodsProperties> queryWrapper, String key) {
        return baseMapper.selectPageByParam(page,queryWrapper);
    }


    @Override
    @Cacheable(cacheNames = "GoodsProperties", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品属性-查询商品属性 ")
    public GoodsProperties getById(Long id) {
        return baseMapper.selectById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsProperties", allEntries = true)
    @Logable(authName = "商品管理-商品属性-新增商品属性")
    public boolean save(GoodsProperties entity) {
        // 主键ID生成
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setDeleted(0);

        QueryWrapper<GoodsProperties> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsProperties::getCompanyId,entity.getCompanyId())
                .eq(GoodsProperties::getPropertyType,entity.getPropertyType())
                .eq(GoodsProperties::getPropertyName,entity.getPropertyName())
                .eq(GoodsProperties::getDeleted,0);

        GoodsProperties old = this.getOne(q);
        if( null != old){
            throw new ServiceException("该租户已存在存在类型["+entity.getPropertyType()+"]的参数名称["+entity.getPropertyName()+"]");
        }

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsProperties", allEntries = true)
    @Logable(authName = "商品管理-商品属性管理-修改商品属性")
    public boolean updateById(GoodsProperties entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());

        QueryWrapper<GoodsProperties> q = new QueryWrapper<>();
        q.lambda()
                .eq(GoodsProperties::getCompanyId,entity.getCompanyId())
                .eq(GoodsProperties::getPropertyType,entity.getPropertyType())
                .eq(GoodsProperties::getPropertyName,entity.getPropertyName())
                .eq(GoodsProperties::getDeleted,0)
                .ne(GoodsProperties::getId,entity.getId());

        GoodsProperties old = this.getOne(q);
        if( null != old){
            throw new ServiceException("该租户已存在存在类型["+entity.getPropertyType()+"]的参数名称["+entity.getPropertyName()+"]");
        }


        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsProperties", allEntries = true)
    @Logable(authName = "商品管理-商品属性管理-删除商品属性")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        GoodsProperties entity = this.getById(id);
        if (entity == null) {
            log.error("删除商品属性异常，无法找到商品属性记录");
            throw new ServiceException("删除商品属性异常，无法找到商品属性记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsProperties", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品属性管理-根据id集合查询商品属性")
    public List<GoodsProperties> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }


    /**
     * 根据类目id, 返回该类目下的所有属性， 以及每个属性的所有属性值
     */
    @Override
    public List<GoodsPropertiesVo> getPropertiesVoList(Long cateId, Long companyId) {

        // 属性返回值列表
        List<GoodsPropertiesVo> propertiesVolist = new ArrayList<>();

        // 根据类目id， 获取该类目下的所有属性id
        List<Long> properIds = goodsCategoryPropertiesService.getProperIdsByCateId(cateId, companyId);
        if (properIds.isEmpty()) {
            return propertiesVolist;
        }

        properIds.stream().forEach(id -> {
            // 根据属性id, 获取属性信息
            GoodsPropertiesVo propertiesVo = baseMapper.getPropertiesVo(id);
            // 根据属性id, 获取该属性的所有属性值信息, getPropertyType： 属性分类
            Object Properties= this.getPropertiesValues(propertiesVo.getPropertyValue(), propertiesVo.getInputType());
            // 关联属性，属性值
            propertiesVo.setPropertiesValues(Properties);
            // 向返回值列表中添加属性信息
            propertiesVolist.add(propertiesVo);
        });
        return propertiesVolist;
    }

    /**
     * 根据属性id 查询属性值
     */
    private Object getPropertiesValues(String propertyValue, Integer inputType) {
        String[]  array= propertyValue.split(",");
        List<String> values = Arrays.asList(array);

        Object object = null;
        List properValues = new ArrayList<>();

        switch (inputType) {
            // 文本
            case 1:
                if (values.isEmpty()) {
                    object = new String("");
                } else {
                    object = new String(values.stream().collect(Collectors.joining(",")));
                };
                break;

            // 单选
            case 2:
            // 多选
            case 3:
                values.stream().forEach(s -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("label", s);
                    map.put("value", s);
                    properValues.add(map);
                });
                object = properValues;
                break;
            default:;
        }
        return object;
    }

}
